//图片方向处理,安卓微信压缩问题hack,IOS6/7压缩扭曲,多张上传
var arr=[]; //图片路径
var j = 1;  //base64转码
//图片上传
var u = navigator.userAgent, app = navigator.appVersion;
var isAndroid = u.indexOf('Android') > -1 || u.indexOf('Linux') > -1; //android终端或者uc浏览器
var isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios终端
//alert('是否是Android：'+isAndroid);
//alert('是否是iOS：'+isiOS);
if(isAndroid) {
    $("#multiple").attr('capture', 'camera');
}

$("#multiple").on('change', function (e) {
    var i = 0,
        notSupport = false;

    var files = e.target.files,
        len = files.length,
        name = "";

    // 循环多张图片，需要for循环和notSupport变量支持（检测）
    for (; i < len; i++) {
        if (files[i]) {
            if(!/image\/\w+/.test(files[i].type)){
                mui.toast("请确保文件为图像类型");
                return false;
            }

            if (!notSupport) {
                (function(i) {
                    //图片方向处理,安卓微信压缩问题hack,IOS6/7压缩扭曲
                    new html5ImgCompress(files[i], {
                        before: function(file) {
                            //console.log('多张: ' + i + ' 压缩前...');
                        },
                        done: function (file, base64) { // 这里是异步回调，done中i的顺序不能保证
                            //console.log('多张: ' + i + ' 压缩成功...');
                            //insertImg(file, j); //处理前
                            name = files[i].name;
                            insertImg(base64, j++, name);
                        },
                        fail: function(file) {
                            //console.log('多张: ' + i + ' 压缩失败...');
                        },
                        complate: function(file) {
                            //console.log('多张: ' + i + ' 压缩完成...');
                        },
                        notSupport: function(file) {
                            notSupport = true;
                            alert('浏览器不支持！');
                        }
                    });
                })(i);
            }
        }
    }
    //console.log(arr);
});

//插入图片
function insertImg(file, j, name) {
    var img = new Image(),
        title, src, size, base;

    if (typeof file === 'object') {
        title = '前';
        size = file.size;
        src = URL.createObjectURL(file);
        base = 1024;
    } else {
        title = '后';
        size = file.length;
        src = file;
        base = 1333;
    }

    //src = file;
    var li=$('<li class="mui-table-view-cell mui-media mui-col-xs-6"></li>');
    img.onload = function() {
        $("<img class='mui-media-object' src="+src+" name="+name+" data-preview-src='' data-preview-group='1'/><div class='mui-media-body' onclick=$(this).prev().parent().remove();delectImg('"+src+"');>删除</div>").appendTo(li);
        console.log('图片' + j + '，名字' + name +'，处理' + title + '质量约：' + (size / base).toFixed(2) + 'KB' + '，尺寸：' + this.width + '*' + this.height);
    };
    $("#imgList").append(li);
    img.src = src;
    arr.push(src);
    file = null; // 处理完清缓存
};


mui.previewImage();

$(function () {
    var orderCode = GetQueryString("orderCode"),
        consumerType = GetQueryString("consumerType"),
        consumerName = GetQueryString("consumerName"),
        consumerIdCard = GetQueryString("consumerIdCard"),
        enterpriseName = GetQueryString("enterpriseName"),
        enterpriseLicence = GetQueryString("enterpriseLicence"),
        wxOrderStatusText = GetQueryString("wxOrderStatusText"),
        applyTime = GetQueryString("applyTime"),
        auditingTime = GetQueryString("auditingTime"),
        signTime = GetQueryString("signTime");

    var payResult = "";
    if(consumerType == "GR"){
        payResult += '<h5>车主姓名：'+ consumerName +'</h5>';
        payResult += '<h5>身份证号：'+ consumerIdCard +'</h5>';
    }else if(consumerType == "QY"){
        payResult += '<h5 style="display: none">企业名称：'+ enterpriseName +'</h5>';
        payResult += '<h5 style="display: none">营业证号：'+ enterpriseLicence +'</h5>';
    }
    payResult += '<h5>申请进度：<span style="color: #ff0000;">'+ wxOrderStatusText +'</span></h5>';
    payResult += '<h5>申请时间：'+ applyTime +'</h5>';
    payResult += '<h5 style="display: none">审核时间：'+ auditingTime +'</h5>';
    payResult += '<h5 style="display: none">签约日期：'+ signTime +'</h5>';
    $("#payInfo").append(payResult);


    //支付凭证提交
    mui(document.body).on('tap', '#ordePayVoucherBtn', function(e) {
        //上传图片为空验证
        if(arr.length==0){
            mui.toast("请选择上传图片");
            return false;
        }

        mui(this).button('loading');

        $.ajax({
            type:"POST",
            url: url + 'weixinOrder/ordePayVoucherSubmit',
            dataType:"json",
            data:{
                "openId":openId,
                "orderCode":orderCode,
                "remark":$.trim($("#note").val())
            },
            cache:false,
            success:function(data){
                console.log(data.data);
                if(data.repCode = "000000"){
                    //图片上传
                    var formdata = new FormData();
                    var imgs = $("#imgList").find("li").find("img");
                    for (var i = 0;i < imgs.length;i++){
                        formdata.append("uploadFileList",dataURItoBlob(imgs[i].src));
                        formdata.append("fileName",imgs[i].name);
                    }
                    formdata.append("bussinessType","FK");
                    formdata.append("orderCode",orderCode);
                    //console.log(formdata.getAll("uploadFileList"));
                    mui.toast("正在上传"+arr.length+"张图片，请稍等...");
                    //附件上传
                    $.ajax({
                        url: url + 'weixinFile/upload',
                        type: "POST",
                        processData: false,
                        contentType: false,
                        data: formdata,
                        success: function(data){
                            console.log(data);
                            if(data.repCode = "000000"){
                                mui.toast("支付凭证上传成功！");
                                var setUrl = "ip_my_apply.html?openId=" + openId;
                                setTimeout("window.location.href='"+setUrl+"'", 1000);
                            }
                        },
                        error:function(){
                            mui('#ordePayVoucherBtn').button('reset');
                            mui.toast("附件上传失败");
                        }
                    });
                }else if(data.repCode == "999999") {
                    mui('#ordePayVoucherBtn').button('reset');
                    mui.toast("认证失败");
                }
            },
            error:function(){
                mui('#ordePayVoucherBtn').button('reset');
                mui.toast("error");
            }
        });
    });



});